package com.deanlib.cabinet.service;

import android.content.Intent;

import com.deanlib.cabinet.app.Constants;
import com.deanlib.cabinet.base.BaseService;
import com.deanlib.cabinet.data.AppDatabase;
import com.deanlib.cabinet.data.model.ResourceCache;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.schedulers.Schedulers;


/**
 * 提供资源缓存的数据库同步
 * 缓存文件可能会被系统或人为的清除，所以需要定期同步
 * @Created by Dean
 * @Date 2023/6/12
 */
public class ResourceCacheService extends BaseService {

    @Override
    public void onCreate() {
        super.onCreate();
//        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        addDisposable(Observable.create(emitter -> {
            File cacheDir = new File(ResourceCache.getCacheDir());
            if (cacheDir.exists() && cacheDir.isDirectory()){
                File[] listFiles = cacheDir.listFiles();
                if (listFiles!=null && listFiles.length>0) {
                    Map<String, String> cacheDict = new HashMap<>();
                    for (File f : listFiles){
                        cacheDict.put(f.getPath(), null);
                    }
                    List<ResourceCache> resourceCaches = AppDatabase.getDaoSession().getResourceCacheDao().loadAll();
                    for (ResourceCache rc : resourceCaches) {
                        if (!cacheDict.containsKey(rc.path) && !cacheDict.containsKey(rc.thumbnailPath)){
                            //数据库记录数据，与本地缓存资源不符，删除数据库数据
                            AppDatabase.getDaoSession().getResourceCacheDao().delete(rc);
                        }
                    }
                }else {
                    AppDatabase.getDaoSession().getResourceCacheDao().deleteAll();
                }
            }
        }).subscribeOn(Schedulers.io()).subscribe());
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getNotifyId() {
        return Constants.SERVICE_NOTIFY_ID_RESOURCE_CACHE;
    }


}
